In this blog I am trying to explain the concept of object class in C#.
Object Class
Object Class is the base class, Object Class supports all classes in the .NET Framework class hierarchy and provides low-level services to derived classes. This is the ultimate base class of all classes in the .NET Framework; it is the root of the type hierarchy.
Languages typically do not require a class to declare inheritance from Object because the inheritance is implicit. Because all classes in the .NET Framework are derived from Object, every method defined in the Object class is available in all objects in the system. Derived classes can and do override some of these methods, including:
· Equals - Supports comparisons between objects.
· Finalize - Performs cleanup operations before an object is automatically reclaimed.
· GetHashCode - Generates a number corresponding to the value of the object to support the use of a hash table.
· ToString - Manufactures a human-readable text string that describes an instance of the class.
Example:
using System;
class Point
{
public int x, y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
public override bool Equals(object obj)
{
if (obj.GetType() != this.GetType()) return false;
Point other = (Point)obj;
return (this.x == other.x) && (this.y == other.y);
}
public override int GetHashCode()
{
return x ^ y;
}
public override String ToString()
{
return String.Format("({0}, {1})", x, y);
}
public Point Copy()
{
return (Point)this.MemberwiseClone();
}
}
public sealed class App
{
static void Main()
{
Point p1 = new Point(1, 2);
Point p2 = p1.Copy();
Point p3 = p1;
Console.WriteLine(Object.ReferenceEquals(p1, p2));
Console.WriteLine(Object.Equals(p1, p2));
Console.WriteLine(Object.ReferenceEquals(p1, p3));
Console.WriteLine("p1's value is: {0}", p1.ToString());
Console.ReadKey();
}
}
Leave Comment